package LiFeedWeb;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import unito.likir.Application;
import unito.likir.io.FileManager;
import unito.likir.Node;
import unito.likir.storage.StorageEntry;

import java.io.IOException;
import java.util.Collection;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author grillo
 */
public class ApplicationManager {

    private final static ApplicationManager app = new ApplicationManager();
    private Application appl;

    private ApplicationManager(){
        try {
            appl = new Application();
            FileManager fileManager = new FileManager();
            Node n;

            n = appl.registerNode("WebNode", 10000);

            n.init(); //the new node is initialized (startup + bootstrap)
        } catch (IOException e) {
            System.err.println("### Errore nella registrazione del nodo, la rete potrebbe non essere avviata");
        }
    }

    public static ApplicationManager getInstance() {
        return app;
    }

    public Application getApplication() {
        return appl;
    }

    public Node getNode() {
        return appl.getNode();
    }

	public Document findUserNews(String user)
	{
        if(appl.getNode().getNodeId() == null)
            return null;
        try
		{
            FileManager fileManager = new FileManager();
            String news = "";
			Collection<StorageEntry> result = appl.getNode().get(fileManager.hash(user+"_pub.xml"), "news", null, true, 10).get();
            news = byteToString(result.iterator().next().getContent().getValue());

            return DocumentHelper.parseText(news);
		}
		catch (Exception e)
		{
			System.err.println(" Errore nella ricerca delle news! \n" + e);
            return null;
		}
	}

    private String byteToString(byte[] arr) {
        String s = "";
        for(int i=0; i<arr.length; i++)
            s += (char)arr[i];
        return s;
    }
}
